﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace W.Purchase.Repository
{
    public class BaseRepository<T> : IRepository<T> where T : class
    {
        private readonly EFCoreDbContext db;

        public BaseRepository(EFCoreDbContext db)
        {
            this.db = db;
        }
        public EFCoreDbContext DB
        {
            get { return db; }
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsaync()
        {
            return await db.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(T t)
        {
            db.Remove(t);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 带条件
        /// </summary>
        /// <param name="expre"></param>
        /// <returns></returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await db.Set<T>().Where(expre).ToListAsync();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
            db.Update(entity);
            return await db.SaveChangesAsync();
        }

        public Task<int> UpdateRangeAsync(List<T> t)
        {
            db.UpdateRange(t);
            return db.SaveChangesAsync();
        }

        public Task<int> AddRangeAsync(List<T> entities)
        {
            db.UpdateRange(entities);
            return db.SaveChangesAsync();
        }
    }
}
